<?php
namespace app\login\controller;

use app\login\model\Account as UserModel;
use think\Request;
use think\Session;

class Account
{
	// 新增用户
	public function add(Request $request)
	{
		$phone 		= $request->param('phone');
		$password 	= $request->param('password');
		$username 	= $request->param('username');
		$age 		= $request->param('age');
		$sex 		= $request->param('sex');
		$code 		= $request->param('code');

        $ret = $this->checkPassword($password); 
        if ($ret != ErrorCode::Success)
            return json(["ErrorCode" => $ret]); 

        $ret = $this->checkPhone($phone); 
		if ($ret != ErrorCode::Success)
            return json(["ErrorCode" => $ret]);

        $ret = $this->checkUserName($username, false); 
		if ($ret != ErrorCode::Success)
            return json(["ErrorCode" => $ret]);

		$ret = $this->checkCode($code);
		if ($ret != ErrorCode::Success)
            return json(["ErrorCode" => $ret]);

		$user = new UserModel;
		$user->Phone = $phone;
		$user->Password = md5($password);
		$user->UserName = $username;
		$user->Age = $age;
		$user->Sex = $sex;
		$user->LoginTime = time();
		$user->LoginArea = "";
		
		if ($user->save())
            return json(["ErrorCode" => ErrorCode::Success]);
		else
		{
			\think\Log::write(sprintf('%s(phone:%s) register error, error msg:%s', $username, $phone, $user->getError()),'error');
            return json(["ErrorCode" => ErrorCode::Fail]);
		}
	}

	// 用户登录
	public function get(Request $request)
	{
		$phone = $request->param('phone');
		$password = $request->param('password');
		$latitude	= $request->param('latitude');
		$longitude = $request->param('longitude');

		$ret = $this->checkPhone($phone, false, false); 
		if ($ret != ErrorCode::Success)
            return json(["ErrorCode"=>$ret, "AccountInfo"=>null]);

        $ret = $this->checkPassword($password); 
		if ($ret != ErrorCode::Success)
            return json(["ErrorCode"=>$ret, "AccountInfo"=>null]);

		$user = UserModel::get(['Phone'=>$phone, 'Password' => md5($password)]);
        if ($user == null)
            return json(["ErrorCode"=>ErrorCode::Password_Error, "AccountInfo"=>null]);
		else
        {
            $ret = [
                "ErrorCode" => ErrorCode::Success,
                "AccountInfo" => [
                    "Phone" => $user->Phone,
                    "Password" => "",
                    "UserName" => $user->UserName,
                    "Age" => $user->Age,
                    "Sex" => $user->Sex,
                    "RegisterTime" => $user->CreateTime,
                    "LastLoginTime" => $user->LoginTime,
					"LastLoginAddress" => $user->LoginAddress,
                ],
            ];
			
			$address = $this->GetLoginAddress($latitude, $longitude);
			$user->LoginAddress = $address;
			if ( false == $user->save() )
			{
				\think\Log::write(sprintf("%s Update LoginAddress error, %s", $phone, $address));
			}
			
            return json($ret); 
        }
	}

	// 查找用户
	protected function find($name)
	{
		$user = UserModel::get(["UserName"=>$name]);
		return $user;
	}

	// 验证账号
	protected function checkUserName($username, $checkExist = true)
	{
        trace(strlen($username));
		if ($username == null || strlen($username) < 2 || strlen($username) > 30)
			return ErrorCode::UserName_Low;
		
		//if (!preg_match("/^[a-zA-Z0-9_]+$/", $username))
		//	return ErrorCode::UserName_Format;
		
		if ($checkExist == true && $this->find($username) != null)
			return ErrorCode::UserName_Exist;
		
		return ErrorCode::Success;
	}
	
	// 验证密码
	protected function checkPassword($password)
	{
		if ($password == null || strlen($password) < 4 || strlen($password) > 10)
			return ErrorCode::Password_Low;
		
		if (!preg_match("/^[a-zA-Z0-9_]+$/", $password))
			return ErrorCode::Password_Fromat; 
		
		return ErrorCode::Success;
	}
	
	// 验证手机号
	protected function checkPhone($phone, $checkExist = true, $json = true)
	{
		if ($phone == null || strlen($phone) != 11)
			return ErrorCode::Phone_Format; 
		
		if (!preg_match("/^\d+$/", $phone))
			return ErrorCode::Phone_Format; 
		
		if ($checkExist == true && UserModel::get(["Phone"=>$phone]) != null)
			return ErrorCode::Phone_Exist;
		
		return ErrorCode::Success;
	}
	
	// 验证码
	protected function checkCode($code)
	{
		if ($code == null || strlen($code) == 0)
			return ErrorCode::Success;

		if (strlen($code) != 6)
			return ErrorCode::Code_Error; 
		
		$sessionCode = session("phonecode");
		if ($sessionCode == null)
			return ErrorCode::Code_Error; 

		if ($sessionCode != $code)
			return ErrorCode::Code_Error; 

		$sessionCodeTime = session("phonecodetime");
		if ($sessionCodeTime != null)
		{
			if (time() - $sessionCodeTime >= 180)
				return ErrorCode::Code_Timeout;
		}
			
		return ErrorCode::Success;
	}
	
	protected function GetLoginAddress($latitude, $longitude)
	{
		if ($latitude == null || $longitude == null)
			return "";
		
		$host = "http://jisujwddz.market.alicloudapi.com";
		$path = "/geoconvert/coord2addr";
		$method = "GET";
		$appcode = "c87b2c80d48449be8eb8e6cb207db61d";
		$headers = array();
		array_push($headers, "Authorization:APPCODE " . $appcode);
		$querys = sprintf("lat=%s&lng=%s&type=baidu", $latitude, $longitude);
		$bodys = "";
		$url = $host . $path . "?" . $querys;

		$curl = curl_init();
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_FAILONERROR, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HEADER, true);
		if (1 == strpos("$".$host, "https://"))
		{
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		}
		$result = curl_exec($curl);	
		$errorCode = curl_errno($curl);
		curl_close($curl);
		trace("GetLoginAddress $errorCode:" . $errorCode);
		if ($errorCode)
		{
			\think\Log::write(sprintf("GetLoginAddress error : %d", $errorCode));
			return "";
		}
		else
		{
			preg_match("/{.*}/", $result, $matches);
			if (count($matches) == 0)
				return "";
			else
			{
				$jsarray = json_decode($matches[0], true);
				trace($jsarray);
				if ($jsarray != null)
				{
					$result = $jsarray['result'];
					if  ($result != null)
						return $result['address'];
				}
			}
			
			return "";
		}
	}
}

abstract class ErrorCode
{
    const Success = 0; 
    const Fail = 1;
    const UserName_Low = 101;
    const UserName_Format = 102;
    const UserName_Exist = 103;
    const Password_Low = 201;
    const Password_Fromat = 202;
    const Password_Error = 203;
    const Phone_Format = 301;
    const Phone_Exist = 302;
    const Phone_NoExist = 303;
	const Code_Error = 401;
    const Code_Timeout = 402;
}


